import axios, { AxiosResponse, InternalAxiosRequestConfig, AxiosError } from 'axios'
import { ResultEnum } from '@/enums/httpEnum'
import { ErrorPageNameMap } from '@/enums/pageEnum'
import { redirectErrorPage, logout } from '@/utils'
import { setCache, getCache, hasCache } from './cache'

const axiosInstance = axios.create({
  baseURL: '',
  timeout: ResultEnum.TIMEOUT
  // withCredentials: true
})

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // if (!config.url?.includes('http') && config.url![0] !== '/') config.url = '/' + config.url
    if (config.url?.includes(import.meta.env.VITE_INFLUXDB_BASE_PATH)) {
      // config.url = import.meta.env.VITE_INFLUXDB_BASE_URL + config.url
      config.headers.Authorization = `Token ${import.meta.env.VITE_INFLUXDB_TOKEN}`
    }
    // else if (config.url === import.meta.env.VITE_JSAPI_BASE_PATH || config.url?.includes('/api/v2/write')) {
    //   config.url = import.meta.env.VITE_JSAPI_BASE_URL + config.url
    // } else if (config.url?.includes('http')) {
    //   config.url = config.url
    // } else {
    //   if (config.url?.includes('/view/upload')) {
    //     config.url = config.url
    //   } else {
    //     config.url = import.meta.env.VITE_CLOUD_BASE_URL + import.meta.env.VITE_CLOUD_BASE_PATH + config.url
    //   }
    //   // '/d/' +
    //   //   window.location.pathname.split('/')[1] +
    // }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    setCache(res.config, res.data)
    const { code } = res.data as { code: number }
    if (code === undefined || code === null) return Promise.resolve(res.data)
    if (code === ResultEnum.DATA_SUCCESS) return Promise.resolve(res.data)
    // 重定向
    if (ErrorPageNameMap.get(code)) redirectErrorPage(code)
    return Promise.resolve(res.data)
  },
  (err: any) => {
    if (err.response.data.code === 401) {
      window.$message.error(err.response.data.msg)
      logout()
    }
    if (err.response.data.code === 403) {
      window.$message.error(err.response.data.msg)
    }
    return Promise.reject(err.response.data)
  }
)

export default axiosInstance
